package com.tarena.lbs.basic.dao.repository.impl;

import com.tarena.lbs.basic.dao.mapper.AreaMapper;
import com.tarena.lbs.basic.dao.repository.AreaRepository;
import com.tarena.lbs.basic.pojo.vo.AreaVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

@Repository
public class AreaRepositoryImpl implements AreaRepository {
    @Autowired
    private AreaMapper areaMapper;
    @Override
    public List<AreaVO> selectAreaList(Integer parentId) {
        List<AreaVO> areaList = areaMapper.selectAreaList(parentId);
        return areaList;
    }

    @Override
    public List<AreaVO> selectChildrenList(Integer parentId) {
        List<AreaVO> childList = areaMapper.selectChildrenList(parentId);
        return childList;
    }

    @Override
    public List<AreaVO> selectAll() {
        // 1. 查询所有区域数据（省、市、区）
        List<AreaVO> allAreas = areaMapper.selectAll();
        // 2. 构建树结构：先找父节点（parentId = 0 代表省级）
        List<AreaVO> treeList = new ArrayList<>();
        for (AreaVO area : allAreas) {
            if (area.getParentId() == 0) { // 省级节点
                treeList.add(buildChildren(area, allAreas));
            }
        }
        return treeList;
    }

    // 递归构建子节点（市→区）
    private AreaVO buildChildren(AreaVO parent, List<AreaVO> allAreas) {
        for (AreaVO area : allAreas) {
            if (area.getParentId().equals(parent.getId())) {
                if (parent.getChildren() == null) {
                    parent.setChildren(new ArrayList<>());
                }
                parent.getChildren().add(buildChildren(area, allAreas));
            }
        }
        return parent;
    }
}
